const { createClient } = require('redis');
let client;
const redisClient = async ()=>{
    if(client){
        return
    }
    client = createClient({
        socket: {
            host: 'localhost',
            port: 6379
        }
    });
    client.on('error', (err) => console.log('Redis Client Error', err));
    await client.connect();
}
/** 
 * ttl 可选，一秒为单位的过期时间，默认不设置
 */
const setkey = async (key,value,ttl = null)=>{
    if(!client) await redisClient();
    await client.set(key, JSON.stringify(value));
    if(ttl !== null){
        await client.expire(key,ttl);
    }
}
const getKey = async (key)=>{
    if(!client) await redisClient();
    const value = await client.get(key);
    return value ? JSON.parse(value) : null;
}

const delKey = async (key)=>{
    if(!client) await redisClient();
    await client.del(key);
}
//清空所有缓存
const flushAll = async ()=>{
    if(!client) await redisClient();
    await client.flushAll();
}
//多事务查询 demo
const findMeryDemo = async (keys) => {
    const [setKeyReply, otherKeyValue] = await client.multi().set('key', 'value').get('another-key').exec(); 
    // ['OK', 'another-value']
}

module.exports = {
    setkey,
    getKey,
    delKey,
    flushAll
}